package com.doge.walknovel.business.home.genres

import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.doge.wnpro.R
import com.doge.walknovel.api.model.StrategyChildInfo
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

object TabHelper {
    fun setupCustomTab(tabLayout: TabLayout, viewPager2: ViewPager2, tabs: List<StrategyChildInfo>) {
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {
                changeTabSelect(tab)
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                changeTabSelect(tab)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                changeTabNormal(tab)
            }
        })
        TabLayoutMediator(
            tabLayout, viewPager2, true
        ) { tab, position ->
            tab.customView = provideCustomTab(tabLayout, tabs[position])
        }.attach()
    }

    private fun provideCustomTab(parent: ViewGroup, tab: StrategyChildInfo): View {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.layout_tab_rank, parent, false)
        val txtView = view as TextView
        txtView.tag = tab
        txtView.text = tab.tabName
        return view
    }

    private fun changeTabSelect(tab: TabLayout.Tab?) {
        val view = tab?.customView ?: return
        val txtView = view as TextView
        txtView.setTextColor(0xFFFF8DA5.toInt())
        txtView.setBackgroundResource(R.drawable.shape_fff5f7_30)
        txtView.typeface = Typeface.DEFAULT_BOLD
    }

    private fun changeTabNormal(tab: TabLayout.Tab?) {
        val view = tab?.customView ?: return
        val txtView = view as TextView
        txtView.setTextColor(0xFF333333.toInt())
        txtView.setBackgroundResource(android.R.color.transparent)
        txtView.typeface = Typeface.DEFAULT
    }
}